var form = layui.form, laydate = layui.laydate, upload = layui.upload, table = layui.table, $ = layui.jquery,
    id = getQueryVariable("id"), newType = getQueryVariable("newType");
layui.use(['tableEdit'], function () {

//签约单位
let complaintUnit = [];
$.ajax({
    url: "company/getAllMakerUnit",
    success: function (res) {
        if (res.status == 200) {
            complaintUnit = res.data;
            $.each(res.data, function (index, item) {
                $("#complaintUnit").append(new Option(item.name, item.code));
            });
            form.render('select');
        } else {
            layer.msg(res.msg, {icon: 5});
        }
    },
    error: function (data) {
        layer.msg("制单公司 查询失败!");
    }
});
//验货公司 供应商
$.ajax({
    url: "customer2/getAllInspectUnit",
    success: function (res) {
        if (res.status == 200) {
            $.each(res.data, function (index, item) {
                $("#company").append(new Option(item.name, item.code));
            });
            form.render('select');
        } else {
            layer.msg(res.msg, {icon: 5});
        }
    },
    error: function (data) {
        layer.msg("验货公司 查询失败!");
    }
});
function selectAddress(code){
    $.ajax({
        type: 'POST',
        url: "customer2/selectByCode",
        data: {"code":code},
        dataType: "json",
        success: function (res) {
            if (res.status == 200) {
                $("#address").val(res.data.address);
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        },
        error: function (data) {
            layer.msg("验货地址 查询失败!");
        }
    });
}

let loginUserCode = user.code;//当前登录用户编码
let executorList = [];
$.ajax({
    url:"user/getAllUserNameAndCode",
    success:function(res){
        if(res.status == 200){
            executorList = res.data;
            for(let i in res.data){
                $("#executor").append("<option value=\"" + res.data[i].code + "\">" + res.data[i].name + "</option>");
                $("#inspector").append("<option value=\"" + res.data[i].code + "\">" + res.data[i].name + "</option>");
            }
            if (id != "") {
                queryById();
            }else{
                $("#executor").val(loginUserCode);
            }
            form.render('select');
        }else{
            layer.msg(res.msg, {icon: 5});
        }
    }
});
let stageList = getdictionary(6,38);//验货阶段列表
let inspectTypeList = getdictionary(6,39);//验货类型列表
for(let i in stageList){
    $("#stageSelect").append("<option value=\"" + stageList[i].code + "\">" + stageList[i].name + "</option>");
}
for(let i in inspectTypeList){
    $("#inspectType").append("<option value=\"" + inspectTypeList[i].code + "\">" + inspectTypeList[i].name + "</option>");
}
let colourList = getdictionary(6, 41);//颜色
let unitList = getdictionary(6, 42);//单位
form.render('select');

let productList = [];
let fileList = [];
let wjCatalogCode = "InspectCargo";//文件编码
let logList = [
    {
        id: "1",
        operationtype: "text1",
        theoperator: "text2",
        operationdate: "text3",
        modifythecontent: "text4"
    }
];

laydate.render({
    elem: '.starttime',
    // type: 'date',
    value: new Date(),
});
laydate.render({
    elem: '.timeLimit',
});

//表单初始值，修改时调用
if (id != "") {
    form.val("editor-form", {
        "executor": "进入修改",
    })
    $("#oddNumber").attr("readonly", true);
}else{
    getLatestOddNumber();
}

function getLatestOddNumber(){
    $.ajax({
        type:'POST',
        url:'inspectCargo/getLatestOddNumber',
        dataType:"json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if (res.data != "") {
                    $("#oddNumber").val(res.data);
                }
            } else {
                layer.msg(res.msg, {icon: 5});
            }
        },
        error: function (data) {
            layer.msg(data.msg, {icon: 5});
        }
    })
}

form.on("select(stage_filter)", function (data) {
    let select_text = data.elem[data.elem.selectedIndex].text;
    $("#stage").val(select_text);
    $("#stageSelect").next().find("dl").css({"display": "none"});
    form.render();
});
$(document).on('input propertychange', "#stage", (function () {
    let values = $("#stage").val();
    $("#stageSelect").val(values);
    form.render();
    $("#stageSelect").next().find("dl").css({"display": "block"});
    let dl = $("#stageSelect").next().find("dl").children();
    let j = -1;
    for (let i = 0; i < dl.length; i++) {
        if (dl[i].innerHTML.indexOf(values) <= -1) {
            dl[i].style.display = "none";
            j++;
        }
        if (j == dl.length - 1) {
            $("#stageSelect").next().find("dl").css({"display": "none"});
        }
    }
}));
//监听提交
form.on('submit(form-element)', function (data) {
    let indexsl = 0;
    let productCache = table.cache["storageproductstableid"];
    /*$.each(productCache, function (index, value) {
        if (typeof (productCache[index]["amount"]) == "undefined" || productCache[index]["amount"] == "") {
            layer.msg("验货质检明细表第" + (index + 1) + "条数量不能为空");
            indexsl++;
            return false;
        } else if (typeof (productCache[index]["price"]) == "undefined" || productCache[index]["price"] == "") {
            layer.msg("验货质检明细表第" + (index + 1) + "条销售单价不能为空");
            indexsl++;
            return false;
        } else if (typeof (productCache[index]["colour"]) == "undefined" || productCache[index]["colour"] == "") {
            layer.msg("验货质检明细表第" + (index + 1) + "条颜色不能为空");
            indexsl++;
            return false;
        } else if (typeof (productCache[index]["priceSubtotal"]) == "undefined" || productCache[index]["priceSubtotal"] == "") {
            layer.msg("验货质检明细表第" + (index + 1) + "条金额小计不能为空");
            indexsl++;
            return false;
        } else if (typeof (productCache[index]["unitCost"]) == "undefined" || productCache[index]["unitCost"] == "") {
            layer.msg("验货质检明细表第" + (index + 1) + "条成本单价不能为空");
            indexsl++;
            return false;
        } else if (typeof (productCache[index]["supplier"]) == "undefined" || productCache[index]["supplier"] == "") {
            layer.msg("验货质检明细表第" + (index + 1) + "条供应商名称不能为空");
            indexsl++;
            return false;
        }
    });*/
    if (indexsl == 0) {
        let flag = false;
        let reqData = data.field;
        reqData["productList"] = productCache;
        reqData["fileList"] = fileList;
        if(id==""){
            flag = insert(reqData);
        }else{
            reqData.id = id;
            flag = update(reqData);
        }
        if (flag) {
            setTimeout(function () {
                //保存成功则刷新提交过来的界面 并关闭此页面
                parent.detab("views/jsp/other/inspection.jsp");
                parent.intab("views/jsp/other/inspection.jsp", "验货")
                parent.detab("views/jsp/other/tpl/newupinspection.jsp" + (id == '' ? '' : '?id=' + id));
            }, 1000);
        }else{
            layer.msg("保存失败",{icon:5});
        }
    }
    return false;
});

//--验货质检明细
table.render({
    elem: '#storageproducts',
    id: 'storageproductstableid',
    data: productList,
    toolbar: '#storageproductstoolbar',
    cellMinWidth :120,
    cols: [[
        {checkbox: true},
        {field: 'productImg', title: '图片', align: 'center', templet: '#imgTpl'},
        {field: 'salesContractNo', title: '销售合同号', sort: true},
        {field: 'loadPlanNo', title: '出运计划单号', sort: true},
        {field: 'purchaseOrderNo', title: '采购单号', sort: true},
        {field: 'productNo', title: '产品编码', sort: true,width: 220},
        {field: 'specNo', title: '规格编码', sort: true},
        {field: 'normExplain', title: '规格说明',style:"overflow:hidden" },
        {field: 'chineseName', title: '中文名称',style:"overflow:hidden" },
        {field: 'englishName', title: '英文名称',style:"overflow:hidden" },
        {field: 'chineseDesc', title: '中文描述',style:"overflow:hidden" },
        {field: 'englishDesc', title: '英文描述',style:"overflow:hidden" },
        {field: 'colour', title: '颜色',/* templet: '#colourScript',*/},
        {field: 'amount', title: '数量', edit: 'text',
            templet: function(d){
                let amount = d.amount?d.amount:0.00; return Number(amount).toFixed(2);
            }
        },
        {field: 'unit', title: '单位', /*templet: '#unitScript',*/},
        {field: 'price', title: '销售单价', edit: 'text',
            templet: function(d){
                let price = d.price?d.price:0.0000; return Number(price).toFixed(4);
            }},
        {field: 'unitCost', title: '成本单价', edit: 'text',
            templet: function(d){
                let unitCost = d.unitCost?d.unitCost:0.0000; return Number(unitCost).toFixed(4);
            }
        },
        {field: 'priceSubtotal', title: '金额小计',
            templet: function(d) {
                if(d.amount==undefined || d.price==undefined){
                    return 0.00;
                }
                return (d.amount*d.price).toFixed(2);
            }
        },
        {field: 'supplier', title: '供应商名称'/*, templet: '#complaintUnitScript'*/},
        {field: 'productType', title: '产品类型',
            templet: function(d) {
                let name = "";
                if(d.productType){
                    if(d.productType==1){
                        name = "成品";
                    }else if(d.productType==1){
                        name = "配件";
                    }
                }
                return name;
            }
        },
        {fixed: 'right', title: '操作', width: 80, align: 'center', toolbar: '#storageproductseditor'},
    ]],
    page: true,
    limit:50,
    height: 380
    , done: function (res, curr, count) {
        let inspectorCode = $("#inspector").val();
        let loadPlanNos = $("#loadPlanNo").val();
        if(res.data.length>0){
            let companyId = res.data[0].companyId;
            if($("#complaintUnit").val()==""){
                $("#complaintUnit").append(new Option(companyId, companyId));
                $("#complaintUnit").val(companyId);
            }
            if(inspectorCode=="undefined" || inspectorCode==""){
                inspectorCode = res.data[0].inspectorCode;
            }
            if(loadPlanNos!=""){
                loadPlanNos+=",";
            }
            $.each(res.data, function (index, item) {
                if(item.loadPlanNo!=undefined){
                    if(loadPlanNos.indexOf(item.loadPlanNo) == -1){
                        loadPlanNos += item.loadPlanNo+",";
                    }
                }else{
                    if(item.purchaseOrderNo!=undefined){
                        if(loadPlanNos.indexOf(item.purchaseOrderNo) == -1){
                            loadPlanNos += item.purchaseOrderNo+",";
                        }
                    }
                }

            });
            if (loadPlanNos.indexOf(",")!=-1){
                loadPlanNos=loadPlanNos.substring(0,loadPlanNos.length-1);
            }
        }
        //业务员 取值第一个产品操作员
        $("#inspector").val(inspectorCode);
        //出运计划单号 拼接
        $("#loadPlanNo").val(loadPlanNos);
        form.render('select');
        hoverOpenImg();//显示大图
        // for (let i in colourList) {
        //     $('.colourSelect').append(new Option(colourList[i].name, colourList[i].code));
        // }
        // for (let i in unitList) {
        //     $('.unitSelect').append(new Option(unitList[i].name, unitList[i].code));
        // }
        // for (let i in complaintUnit) {
        //     $('.complaintUnitSelect').append(new Option(complaintUnit[i].name, complaintUnit[i].code));
        // }
        for (let i = 0; i < res.data.length; i++) {
            let tempId = res.data[i].tempId!=undefined?res.data[i].tempId:i;
            // $("#colour_" + tempId).val(res.data[i].colour);
            // $("#unit_" + tempId).val(res.data[i].unit);
            // $("#complaintUnit_" + tempId).val(res.data[i].supplier);
        }
        form.render('select');
    }
});

table.on('edit(storageproductstable)', function (obj) {
    let old = $(this).prev().text();//旧值
    //判断数据类型
    if ((obj.field == "amount" || obj.field == "price" || obj.field == "priceSubtotal") && !isNumber(obj.value)) {
        layer.msg('请输入数字');
        $(this).val(old);
        return;
    }
    obj.update({
        priceSubtotal:(obj.data.amount*obj.data.price).toFixed(2)
    })
});

form.on("select(colourSelect_filter)", function (data) {
    let elem = data.othis.parents("tr");
    let dataIndex = elem.attr("data-index");
    let tableData = table.cache["storageproductstableid"];
    $.each(tableData, function (index, value) {
        if (value.LAY_TABLE_INDEX == dataIndex) {
            tableData[index]["colour"] = data.value;
        }
    });
});
form.on("select(unitSelect_filter)", function (data) {
    let elem = data.othis.parents("tr");
    let dataIndex = elem.attr("data-index");
    let tableData = table.cache["storageproductstableid"];
    $.each(tableData, function (index, value) {
        if (value.LAY_TABLE_INDEX == dataIndex) {
            tableData[index]["unit"] = data.value;
        }
    });
});

form.on("select(complaintUnitSelect_filter)", function (data) {
    let elem = data.othis.parents("tr");
    let dataIndex = elem.attr("data-index");
    let tableData = table.cache["storageproductstableid"];
    $.each(tableData, function (index, value) {
        if (value.LAY_TABLE_INDEX == dataIndex) {
            tableData[index]["supplier"] = data.value;
        }
    });
});

table.on('tool(storageproductstable)', function (obj) {
    if (obj.event === 'del') {
        layer.confirm('确认删除?', function (index) {
            let oldData =  table.cache["storageproductstableid"];
            for (let i = 0; i < oldData.length; i++) {
                if (oldData[i].tempId == obj.data.tempId) {
                    oldData.splice(i, 1);
                    i--;
                    table.reload('storageproductstableid',{data : oldData});
                    break;
                }
            }
            layer.msg("删除成功", {icon: 6});
            layer.close(index);
        });
    }
});

form.on("select(company_filter)", function (data) {
    selectAddress(data.value);
});

table.on('toolbar(storageproductstable)', function (obj) {
    let checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'importshipmentplan':
            layer.open({
                type: 2,
                area: $(window).width() < 458 ? "['100%', '100%']" : ['75%', '75%'],
                content: 'views/jsp/other/tpl/importshipmentplan.jsp'
            });
            break;
        case 'importpurchasedocuments':
            layer.open({
                type: 2,
                area: $(window).width() < 458 ? "['100%', '100%']" : ['75%', '75%'],
                content: 'views/jsp/other/tpl/importpurchasedocuments.jsp'
            });
            break;
        case 'del':
            let data = checkStatus.data, delList = [];
            data.forEach(function (n, i) {
                delList.push(n.id);
            });
            if (delList != '') {
                layer.confirm('确定删除所选项吗？', function (index) {
                    let cbList = table.cache["storageproductstableid"];
                    for (let i = 0; i < cbList.length; i++) {
                        delList.forEach((item, index) => {
                            //当数组中任意一个元素的rowIndex值与取消复选框的元素对象属性rowIndex的下标值相等，则在数组中删除该元素
                            if (typeof (cbList[i]) != "undefined" && item == cbList[i].id) {
                                cbList.splice(i, 1);
                            }
                        })
                    }
                    table.reload("storageproductstableid", {
                        data: cbList,
                    });
                    layer.msg('删除成功');
                })
            } else {
                layer.msg('请选择需要删除的行');
            }
            break;
    }
    ;
});

function hoverOpenImg() {
    let img_show = null; // tips提示
    $("body").delegate("td img", "mouseover", function () {
        let img = "<img class='img_msg' src='" + $(this).attr('src') + "' style='width:130px;' />";
        img_show = layer.tips(img, this, {
            tips: [2, 'rgba(41,41,41,.5)']
            , area: ['160px']
        });
    });
    $("body").delegate("td img", "mouseout", function () {
        layer.close(img_show);
    });
}

//---附件
table.render({
    elem: '#attachment'
    , data: fileList
    , toolbar: '#attachmenttoolbar'
    , cols: [[
        {field: 'wjName', title: '文件名称', fixed: true,style:"overflow:hidden"},
        // {field: 'fileName', title: '文件名称', fixed: true,style:"overflow:hidden"},
        {field: 'fileUrl', title: '文件路径', fixed: true,style:"overflow:hidden"},
        {field: 'fileType', title: '文件类型', fixed: true},
        {field: 'fileSize', title: '文件大小(KB)', fixed: true},
        {field: 'fileExecutor', title: '操作员', fixed: true,
            templet: function(data) {
                let name = "";
                $.each(executorList, function(index, item) {
                    if (data.fileExecutor==item.code){
                        name = item.name;
                        return ;
                    }
                });
                return name;
            }
        },
        {field: 'fileUploadTime', title: '上传时间', fixed: true,
            templet: function(d) {
                return layui.util.toDateString(d.createTime,"yyyy-MM-dd");
            }
        },
        {fixed: 'right', width: 180, align: 'center', toolbar: '#attachmenteditor', title: '操作'},
    ]]
    , id: 'attachmenttableid'
    , height: 380
    , page: true
});
upload.render({
    elem: '#uploadfile'
    , url: 'ftp/uploadFile'
    , field: 'uploadify'
    , accept: 'file'
    , data:{"fileType":"inspectCargo"}
    , multiple: true
    , auto: false
    , bindAction: '#testListAction'
    , choose: function (obj) {
        var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
        //读取本地文件
        obj.preview(function (index, file, result) {
            var newfilename = "";
            if (ispd(wjCatalogCode, file.name)) {
                // newfilename = getFileName(file.name);
                // layer.msg("此目录下已存在重名的文件，已自动对本文件进行了重命名！");
                layer.confirm('已存在同名的文件，是否覆盖？', function (index) {
                    layer.close(index);
                });
            }
            if (newfilename != "") {
                var obj = {};
                obj.code = index;
                obj.name = newfilename;
                fileList.push(obj);
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + newfilename + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    // fileListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    var fileListIns = [];
                    for (var i = 0; i < fileList.length; i++) {
                        if (index != fileList[i].code) {
                            fileListIns.push(fileList[i]);
                        }
                    }
                    fileList = fileListIns;
                });

                $("#uploadlist").append(tr);
            }else{
                var obj = {};
                obj.code = index;
                obj.name = file.name;
                // fileList.push(obj);
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs demo-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger demo-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.demo-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.demo-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    // fileListIns.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                    var fileListIns = [];
                    for (var i = 0; i < fileList.length; i++) {
                        if (index != fileList[i].code) {
                            fileListIns.push(fileList[i]);
                        }
                    }
                    fileList = fileListIns;
                });

                $("#uploadlist").append(tr);
            }
        });
    }
    , done: function (res, index, upload) {
        var filename = "";
        for (var i = 0; i < uploadlist.length; i++) {
            if (uploadlist[i].code == index) {
                filename = uploadlist[i].name;
                break;
            }
        }
        if (res.data.length > 0) {
            var files = res.data;
            var filepaths = [];
            for (var i = 0; i < files.length; i++) {
                var obj = {};
                obj.fileName = files[i].fileName;
                obj.ftpPath = files[i].ftpPath;
                filepaths.push(obj);
            }
            if (savefile(filepaths, filename, wjCatalogCode)) {
                let oldData = fileList;
                let newData = [];
                let num = oldData.length+1;
                for(let i in files){
                    let newFile = {};
                    // fileList[i].tempId = num;
                    newFile.fileName = files[i].fileName;
                    newFile.wjName = files[i].originalFileName;
                    newFile.fileUrl = files[i].ftpPath;
                    newFile.fileSize = (this.files[index].size / 1024).toFixed(1);
                    newData.push(newFile);
                    num++;
                }
                oldData.push.apply(oldData, newData);
                fileList = oldData;
                table.reload('attachmenttableid', {data:fileList});
            }

            var tr = $("#uploadlist").find('tr#upload-' + index), tds = tr.children();
            tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
            tds.eq(3).html(''); //清空操作
            return delete this.files[index]; //删除文件队列已经上传成功的文件
        }
        /* if (res.files.file) { //上传成功
             var tr = $("#uploadlist").find('tr#upload-' + index)
                 , tds = tr.children();
             tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
             tds.eq(3).html(''); //清空操作
             return delete this.files[index]; //删除文件队列已经上传成功的文件
         }*/
        this.error(index, upload);
    }
    , error: function (index, upload) {
        let tr = $("#uploadlist").find('tr#upload-' + index), tds = tr.children();
        tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
        tds.eq(3).find('.demo-reload').removeClass('layui-hide'); //显示重传
    }
});

table.on('toolbar(attachmenttable)', function (obj) {
    let checkStatus = table.checkStatus(obj.config.id);
    switch (obj.event) {
        case 'uploadfile':
            $("#uploadlist").html(""); //清空上传列表数据
            layer.open({
                type: 1,
                title: "文件上传",
                area: ['710px', '340px'],
                content: $("#attachmentupload")//引用的弹出层的页面层的方式加载修改界面表单
                , cancel: function (index, layero) {
                    table.reload('attachmenttableid', {}); //点击关闭刷新表格
                }
            });
            break;
    };
});
table.on('tool(attachmenttable)', function (obj) {
    let data = obj.data;
    if (obj.event === 'download') { //下载
        downFileLoad(data.fileUrl+'/'+data.fileName);
    } else if (obj.event === 'del') {
        layer.confirm('确认删除吗？', function (index) {
            let oldData =  fileList;
            for (let i = 0; i < oldData.length; i++) {
                if (oldData[i].tempId == obj.data.tempId) {
                    oldData.splice(i, 1);
                    i--;
                    table.reload('attachmenttableid',{data : oldData});
                    break;
                }
            }
            layer.msg("删除成功", {icon: 6});
            layer.close(index);
        });
    }
});

//---操作日志
table.render({
    elem: '#otherwarehouselog'
    , data: logList
    , cols: [[
        {field: 'operationtype', title: '操作类型', fixed: true}
        , {field: 'theoperator', title: '操作员'}
        , {field: 'operationdate', title: '操作日期'}
        , {field: 'modifythecontent', title: '修改内容'}
    ]]
    , id: 'logtableid'
    , height: 380
    , limit: 30//显示的数量
    , page: true
});

function isNumber(val) {
    let regPos = /^\d+(\.\d+)?$/; //非负浮点数
    let regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
    if (regPos.test(val) || regNeg.test(val)) {
        return true;
    } else {
        return false;
    }
}

function queryById() {
    $.ajax({
        type: 'POST',
        // data:{"id":id},
        url: 'inspectCargo/selectByKey/' + id,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        success: function (res) {
            if (res.status == 200) {
                if(res.data){
                    let oddNumber = "";
                    let boxStatus = $("#boxStatus").val();
                    if(1==newType){
                        getLatestOddNumber()
                        oddNumber = $("#oddNumber").val()
                        //待验货箱-草稿箱
                        if(boxStatus==0){
                            boxStatus = 1;
                        }
                    }else{
                        oddNumber = res.data.oddNumber;
                        boxStatus = res.data.boxStatus;
                    }
                    let inspectTime = new Date();
                    if(res.data.inspectTime){
                        inspectTime = res.data.inspectTime;
                    }
                    laydate.render({
                        elem: '.starttime',
                        value: inspectTime,
                    });
                    form.val("editor-form", {
                        "oddNumber": oddNumber,
                        "inspectType": res.data.inspectType,
                        // "inspectTime": res.data.inspectTime,
                        "address": res.data.address,
                        "timeLimit": res.data.timeLimit,
                        "reportNo": res.data.reportNo,
                        "loadPlanNo": res.data.loadPlanNo,
                        "inspector": res.data.inspector,
                        "cost": res.data.cost,
                        "stage": res.data.stage,
                        "complaintUnit": res.data.complaintUnit,
                        "executor": res.data.executor,
                        "remark": res.data.remark,
                        "company":res.data.company,
                        "boxStatus": boxStatus,
                    });
                    let companyId = res.data.companyId;
                    if($("#complaintUnit").val()==""){
                        $("#complaintUnit").append(new Option(companyId, companyId));
                        $("#complaintUnit").val(companyId);
                    }

                    productList = queryProductByIcId(id);
                    table.reload('storageproductstableid',{data : productList});
                    fileList = queryFileByIcId(id);
                    table.reload('attachmenttableid',{data : fileList});
                }else{
                    layer.msg("初始化失败!");
                }
            } else {
                layer.msg("初始化失败!");
            }
        },
        error: function (data) {
            layer.msg("初始化失败!");
        }
    });
}

//产品
function queryProductByIcId(icId) {
    let obj = [];
    $.ajax({
        type: 'POST',
        url: 'inspectCargo/selectProductByIcId/'+icId,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if(res.data.length>0){
                    obj = res.data;
                    form.val("editor-form", {
                        "productNo": res.data.productNo,
                        "specNo": res.data.specNo,
                        "normExplain": res.data.normExplain,
                        "chineseName": res.data.chineseName,
                        "englishName": res.data.englishName,
                        "chineseDesc": res.data.chineseDesc,
                        "englishDesc": res.data.englishDesc,
                        "unit": res.data.unit,
                        "colour": res.data.colour,
                        "customerArticleNo": res.data.customerArticleNo,
                        "price": res.data.price,
                        "amount": res.data.amount,
                        "priceSubtotal": res.data.priceSubtotal,
                        "supplier": res.data.supplier,
                        "unitCost": res.data.unitCost,
                        "salesContractNo": res.data.salesContractNo,
                        "purchaseOrderNo": res.data.purchaseOrderNo,
                    })
                }else{
                    // layer.msg(res.msg, {icon : 0})
                }
            }else{
                layer.msg("产品初始化失败!");
            }
        },
        error: function (data) {
            layer.msg("产品初始化失败!");
        }
    });
    return obj;
}
//附件
function queryFileByIcId(icId) {
    let obj = [];
    $.ajax({
        type: 'POST',
        url: 'inspectCargo/selectFileByIcId/'+icId,
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if (res.data.length>0){
                    obj = res.data;
                    form.val("editor-form", {
                        "wjName": res.data.wjName,
                        // "fileName": res.data.fileName,
                        "fileUrl": res.data.fileUrl,
                        "fileType": res.data.fileType,
                        "fileSize": res.data.fileSize,
                        "fileExecutor": res.data.fileExecutor,
                        "fileUploadTime": res.data.fileUploadTime,
                    })
                }else{
                    // layer.msg("暂无附件数据",{icon:3});
                }
            }else{
                layer.msg(res.msg,{icon:3});
            }
        },
        error: function (data) {
            layer.msg("附件初始化失败!");
        }
    });
    return obj;
}

function insert(data) {
    let tf = false;
    $.ajax({
        type: 'POST',
        data: JSON.stringify(data),
        url: 'inspectCargo/insert',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if (res.data>0) {
                    tf = true;
                    layer.msg("添加成功!");
                } else {
                    layer.msg(res.msg+" 添加失败");
                }
            } else {
                layer.msg(res.msg+" 添加失败");
            }
        },
        error: function (data) {
            layer.msg("添加失败!");
        }
    });
    return tf;
}

function update(data) {
    let tf = false;
    $.ajax({
        type: 'POST',
        data: JSON.stringify(data),
        url: 'inspectCargo/update',
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if (res.data>0) {
                    tf = true;
                    layer.msg("修改成功!");
                }
            }else{
                layer.msg("修改失败!");
            }
        },
        error: function (data) {
            layer.msg("修改失败!");
        }
    });
    return tf;
}

$('#generateNumber').on('click', function () {
    // let time = new Date().Format("yyyy-MM-dd HH:mm:ss.SSS");//可改为 自定义时间 字符串
    let dataJson = {
        "type":"YH",
        // "time": time
    };
    $.ajax({
        type: 'POST',
        url: 'number/numberByTypeAndDate',
        data: JSON.stringify(dataJson),
        dataType: "json",
        contentType: 'application/json;charset=utf-8',
        async: false,
        success: function (res) {
            if (res.status == 200) {
                if (res.data!=""){
                    form.val("editor-form", {
                        "oddNumber": res.data,
                    })
                }
            }else{
                layer.msg(res.msg,{icon:5});
            }
        },
        error: function (data) {
            layer.msg(data.msg,{icon:5});
        }
    });
});

//获取文件目录下所有的文件名
function ispd(wjCatalogCode, filename) {
    /* fileNames=[];*/
    var cun = false;
    $.ajax({
        type: 'get',
        //  url : 'resource/getTree',
        data: {"wjCatalogCode": wjCatalogCode, "name": filename},
        url: 'wjinfo/ispd',
        dataType: "json",
        /*  contentType: 'application/json',*/
        async: false,
        success: function (da) {
            if (da.status == 200) {
                cun = da.data == 0 ? false : true;

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return cun;
    // return obj;
}

function getFileName(filename) {
    /* fileNames=[];*/
    var cun = "";
    $.ajax({
        type: 'get',
        //  url : 'resource/getTree',
        data: {"filename": filename},
        url: 'wjinfo/getFileName',
        dataType: "json",
        /*  contentType: 'application/json',*/
        async: false,
        success: function (da) {
            if (da.status == 200) {
                cun = da.data;

            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return cun;
    // return obj;
}

//判断文件名是否重复
function iscf(filename) {
    var tf = false;
    for (var i = 0; i < fileNames.length; i++) {
        if (filename == fileNames[i]) {
            tf = true;
            break;
        }
    }
    return tf;
}

//保存上传的文件
function savefile(filepaths, filename, wjCatalogCode) {
    var tf = false;
    $.ajax({
        type: 'post',
        data: {
            "files": JSON.stringify(filepaths), "wjCatalogCode": JSON.stringify(wjCatalogCode),
            "name": JSON.stringify(filename)
        },
        url: 'wjinfo/savefile',
        dataType: "json",
        async: false,
        success: function (da) {
            if (da.status == 200) {
                tf = da.data == 0 ? false : true;
            }
        },
        error: function (data) {
            // layer.msg("获取失败!");
        }
    });
    return tf;
}

});